<template>
  <el-dialog v-model="dialogVisible" title="修改密码" width="500px" draggable>
    <el-form :model="passwordForm" label-width="100px" :rules="rules" ref="formRef">
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input v-model="passwordForm.oldPassword" show-password />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="passwordForm.newPassword" show-password />
        <div class="password-strength-hint" v-if="passwordForm.newPassword">
          密码强度:
          <span :class="getStrengthClass(calculatePasswordStrength(passwordForm.newPassword))">
            {{ getStrengthText(calculatePasswordStrength(passwordForm.newPassword)) }}
          </span>
          <div class="strength-bar">
            <div :class="`strength-level ${getStrengthLevelClass(calculatePasswordStrength(passwordForm.newPassword))}`"></div>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="passwordForm.confirmPassword" show-password />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ElNotification } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { updatePassword } from "@/api/modules/user";
import { useUserStore } from "@/stores/modules/user";

const dialogVisible = ref(false);
const passwordForm = ref({
  oldPassword: "",
  newPassword: "",
  confirmPassword: ""
});

const formRef = ref<FormInstance>();
const rules = ref<FormRules>({
  oldPassword: [
    { required: true, message: "请输入旧密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度在6到20个字符", trigger: "blur" }
  ],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 8, max: 20, message: "密码长度在8到20个字符", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        const strength = calculatePasswordStrength(value);
        if (strength < 2) {
          callback(new Error("密码强度不足，请使用更复杂的组合"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  confirmPassword: [
    { required: true, message: "请确认新密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error("两次输入密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
});

const openDialog = () => {
  dialogVisible.value = true;
};

const handleSubmit = async () => {
  try {
    const valid = await formRef.value?.validate().catch(() => false);
    if (!valid) return false;
    let param = {
      password_old: passwordForm.value.oldPassword,
      password_new: passwordForm.value.newPassword,
      id: useUserStore().userInfo.id
    };
    const isValid = await updatePassword(param);
    if (isValid) {
      // 模拟提交请求
      ElNotification({
        title: "成功",
        message: "密码修改成功，请重新登录",
        type: "success"
      });

      dialogVisible.value = false;
    }
  } catch (error) {
    // ElNotification({
    //   title: "错误",
    //   message: error instanceof Error ? error.message : "密码修改失败",
    //   type: "error"
    // });
    console.log(error);
  }
};

// 计算密码强度等级
const calculatePasswordStrength = (password: string): number => {
  let strength = 0;

  // 长度至少8字符
  if (password.length >= 8) strength += 1;

  // 包含小写字母
  if (/[a-z]/.test(password)) strength += 1;

  // 包含大写字母
  if (/[A-Z]/.test(password)) strength += 1;

  // 包含数字
  if (/\d/.test(password)) strength += 1;

  // 包含特殊字符
  if (/[^a-zA-Z0-9]/.test(password)) strength += 1;

  return strength;
};

// 获取强度文本
const getStrengthText = (strength: number): string => {
  switch (strength) {
    case 0:
    case 1:
      return "弱";
    case 2:
    case 3:
      return "中";
    case 4:
    case 5:
      return "强";
    default:
      return "";
  }
};

// 获取强度类名
const getStrengthClass = (strength: number): string => {
  switch (strength) {
    case 0:
    case 1:
      return "weak";
    case 2:
    case 3:
      return "medium";
    case 4:
    case 5:
      return "strong";
    default:
      return "";
  }
};

// 获取强度条类名
const getStrengthLevelClass = (strength: number): string => {
  switch (strength) {
    case 0:
    case 1:
      return "weak-bg";
    case 2:
      return "medium-bg";
    case 3:
    case 4:
    case 5:
      return "strong-bg";
    default:
      return "";
  }
};
defineExpose({ openDialog });
</script>

<style scoped>
.password-strength-hint {
  margin-top: 8px;
  font-size: 14px;
  color: #666;
}

.strength-bar {
  height: 5px;
  background-color: #e0e0e0;
  border-radius: 3px;
  margin-top: 6px;
  overflow: hidden;
}

.strength-level {
  height: 100%;
  border-radius: 3px;
  transition: width 0.3s ease;
}

.weak {
  color: #ff4949;
}

.medium {
  color: #e6a23c;
}

.strong {
  color: #67c23a;
}

.weak-bg {
  width: 20%;
  background-color: #ff4949;
}

.medium-bg {
  width: 60%;
  background-color: #e6a23c;
}

.strong-bg {
  width: 100%;
  background-color: #67c23a;
}
</style>
